import os
from django.conf import settings
from django.http import JsonResponse
from django.views import View
from alipay import AliPay
from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from meiduo_mall.utils.views import LoginRequiredJSONMixin


"""
保存订单支付结果接口文档：
    请求方式：　GET
    路由：    payment/status
    参数：路径参数
    响应：json   code  errmsg  trade_id
"""
class PaymentStatusView(View):
    def get(self, request):
        # 接收 支付宝返回的参数 ---查询参数
        params = request.GET  # queryDict
        data_dict = params.dict()  # queryDict - -dict() ==> dict

        # 剔除 sign
        signature = data_dict.pop('sign')

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,

            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),

            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 让支付宝 校验参数的准确性
        success = alipay.verify(data_dict, signature)

        if success:
            # 校验通过
            # 4.存入 数据表
            Payment.objects.create(
                order=data_dict.get('out_trade_no'),
                trade_id=data_dict.get('trade_no'),
            )
            # 5. 更改订单状态 为待评价
            OrderInfo.objects.filter(
                pk=data_dict.get('out_trade_no'),
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
            ).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )
            return JsonResponse({'code': 0, 'errmsg': 'OK', 'trade_id': data_dict.get('trade_no')})
        # 返回响应
        else:
            return JsonResponse({'code': 400, 'errmsg': '非法交易'})


"""
订单支付功能接口文档：
    请求方式：　　GET
    路由：    /payment/<int:order_id>/
    参数：路径参数    orderid订单编号   int  　必传
    响应：json    code errmsg   alipay_url支付宝登录链接
"""
class PaymentView(LoginRequiredJSONMixin, View):
    def get(self, request, order_id):
        try:
            order = OrderInfo.objects.get(user=request.user, pk=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            return JsonResponse({'code': 0, 'errmsg': '订单不存在!'})

        # 实例化 --传必传的参数
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,

            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),

            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 调用函数 order_string = api_alipay_trade_page_pay()
        order_string = alipay.api_alipay_trade_page_pay(
            subject="美多商城",
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )

        # 支付链接 https://openapi.alipaydev.com/gateway.do + ? + '加过密的参数' api_alipay_trade_page_pay()
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        # 返回
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'alipay_url': alipay_url})
































